package com.isoft.airportsystem.service.impl.change;

import com.isoft.airportsystem.entity.change.NotificationRecord;
import com.isoft.airportsystem.entity.dao.FlightChangeEvent;
import com.isoft.airportsystem.mapper.change.NotificationRecordMapper;
import com.isoft.airportsystem.service.change.EmailNotificationService;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


// 邮件通知服务实现
@Slf4j
@Service
public class EmailNotificationServiceImpl implements EmailNotificationService {

    private final JavaMailSender mailSender;
    private final NotificationRecordMapper recordMapper;

    @Value("${spring.mail.username:3535427400@qq.com}")  // 发件人邮箱
    private String fromEmail;

    @Value("${spring.mail.nickname:机场航班通知中心}")  // 邮件昵称
    private String emailNickname;

    public EmailNotificationServiceImpl(JavaMailSender mailSender,
                                        NotificationRecordMapper recordMapper) {
        this.mailSender = mailSender;
        this.recordMapper = recordMapper;
    }

    @Override
    @Async("emailTaskExecutor")  // 异步执行
    public void sendEmailNotification(String subscriptionId, String to, String subject, String content) {
        NotificationRecord record = createNewRecord(subscriptionId, to);

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(new InternetAddress(fromEmail, emailNickname));
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(buildHtmlContent(content), true);

            mailSender.send(message);
            record.setSendStatus("SUCCESS");
        } catch (Exception e) {
            record.setSendStatus("FAILED");
            record.setErrorMessage(e.getMessage());
            log.error("邮件发送失败: {}", e.getMessage());
        }

        recordMapper.insert(record);
    }

    @Override
    @Async("emailTaskExecutor")  // 异步执行
    public void sendFlightChangeNotification(String subscriptionId, FlightChangeEvent event, String toEmail) {
        NotificationRecord record = createNewRecord(subscriptionId, toEmail);

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(new InternetAddress(fromEmail, emailNickname));
            helper.setTo(toEmail);
            helper.setSubject(buildSubject(event));
            helper.setText(buildContent(event), true);

            mailSender.send(message);
            record.setSendStatus("SUCCESS");
        } catch (Exception e) {
            log.error("发送航班变更通知失败: {}", e.getMessage());
            record.setSendStatus("FAILED");
            record.setErrorMessage(e.getMessage());
        }

        recordMapper.insert(record);
    }

    // 构建邮件标题
    private String buildSubject(FlightChangeEvent event) {
        return "航班" + event.getFlightId() + "变更通知(" + event.getChangeType() + ")";
    }

    // 构建邮件内容
    private String buildContent(FlightChangeEvent event) {
        StringBuilder html = new StringBuilder();
        html.append("<div style='font-family:Arial,sans-serif;max-width:600px;margin:auto;'>");
        html.append("<div style='background:#1565c0;color:#fff;padding:16px 24px;font-size:20px;font-weight:bold;'>航班变更通知</div>");
        html.append("<div style='background:#f5f7fa;padding:24px;'>");
        html.append("<p>您的航班变更申请已通过审核，具体变更内容如下：</p>");

        // 解析changeData
        try {
            ObjectMapper mapper = new ObjectMapper();
            java.util.List<java.util.Map<String, String>> changes = mapper.readValue(
                    event.getChangeData(),
                    new TypeReference<java.util.List<java.util.Map<String, String>>>() {}
            );
            if (changes != null && !changes.isEmpty()) {
                html.append("<table border='1' cellpadding='6' style='border-collapse:collapse;width:100%;margin:16px 0;'>");
                html.append("<tr style='background:#e3eafc;'><th>字段</th><th>变更前</th><th>变更后</th></tr>");
                for (java.util.Map<String, String> change : changes) {
                    html.append("<tr><td>")
                            .append(change.getOrDefault("field", "")).append("</td><td>")
                            .append(change.getOrDefault("old", "")).append("</td><td>")
                            .append(change.getOrDefault("new", "")).append("</td></tr>");
                }
                html.append("</table>");
            } else {
                html.append("<p>无字段变更。</p>");
            }
        } catch (Exception e) {
            html.append("<p>变更详情解析失败</p>");
        }

        html.append("<p>审核人：").append(event.getOperator()).append("</p>");
        html.append("<p>审核时间：").append(event.getEventTime()).append("</p>");
        html.append("<p style='color:#888;font-size:12px;'>此为系统自动发送邮件，请勿直接回复。</p>");
        html.append("</div></div>");
        return html.toString();
    }

    // 构建HTML邮件内容
    private String buildHtmlContent(String textContent) {
        return """
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset='UTF-8'>
                <style>
                    body { font-family: Arial, sans-serif; }
                    .container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; }
                    .header { background-color: #0066cc; padding: 15px; color: white; }
                    .content { margin: 20px 0; padding: 20px; background-color: #f9f9f9; }
                    .footer { margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee; color: #6c757d; font-size: 12px; }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h2>航班管理系统通知</h2>
                    </div>
                    <div class="content">
                        %s
                    </div>
                    <div class="footer">
                        <p>此为系统自动发送邮件，请勿直接回复</p>
                    </div>
                </div>
            </body>
            </html>
            """.formatted(textContent);
    }

    // 创建新的通知记录
    private NotificationRecord createNewRecord(String subscriptionId, String to) {
        NotificationRecord record = new NotificationRecord();
        record.setRecordId(UUID.randomUUID().toString());
        record.setSubscriptionId(subscriptionId);  // 关键修复：设置订阅ID
        record.setNotificationType("EMAIL");
        record.setNotificationAddress(to);
        record.setSendTime(new Date());
        return record;
    }
}